package composer;

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;

import composer.base.Note;
import composer.base.Track;
import composer.gui.PianoRollScreen;
import composer.gui.Screen;

public class ComposerController {

	private Screen firstScreen;
	private Screen currentScreen;
	private boolean shouldStop;
	private MIDlet composerMidlet;
	private double fps = 20;

	public ComposerController(MIDlet midlet) {
		Track track = new Track((byte)0);
		track.addNote(new Note(60, 127, 0, 3));
		track.addNote(new Note(62, 127, 3, 3));

		this.firstScreen = new PianoRollScreen(track);
		this.composerMidlet = midlet;
	}

	public void start() {
		this.changeToScreen(firstScreen);
		this.update();
	}

	public void changeToScreen(Screen screen) {
		this.currentScreen = screen;
		this.currentScreen.enter();
		Display.getDisplay(this.composerMidlet).setCurrent((Displayable) this.currentScreen);
	}

	private void update() {
		long timePerFrame = (long) (1000 / fps); 
		while (!shouldStop) {
			long startTime = System.currentTimeMillis();
			
			this.currentScreen.update();
			this.currentScreen.paint();
			
			long endTime = System.currentTimeMillis();
			long delta = endTime - startTime;
			delta = delta - timePerFrame;

			if(delta > 0){
				try {
					Thread.sleep(delta);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
